# coding:utf-8

"""
CopyRight(c)  2017-09-15  Fraplus Corp

Author: Xiaodong.yang
Email:  xiaodong.yang@unidt.com
Functions:

we chat server

dependence package:

fralog
handler

"""
import json
import tornado.ioloop
import tornado.web
from tornado.web import RequestHandler, HTTPError

import hashlib

from handler.FraHandler import FraHandler
from handler.signalhandler import SigProccess
from fralog.FraLog import Fralog
import urllib

log = Fralog().getFileLog()


class WeChatHandlerNoJewellery(FraHandler):
    """
    该类实际上并无存在的必要，将逐步删除对该类的依赖
    原因： 该类的存在导致部署新客户变得麻烦，需要修改重定向的链接
            扩展性太差
    """

    def get(self, channel, wechat_from):
        """

        :param channel: 
        :param wechat_from: 微信的OPENID，该值指示此次分享者的openid
        :return: 
        """
        log.debug('Get Request')
        log.debug('Channel is:%s' % (channel))
        #
        # 跳转至该链接时，会自动加上?openid参数
        openid = self.get_argument('openid')
        log.info("openid=%s" % (openid))
        url = 'http://www.fenweiplus.com/test?channel=%s&openid=%s&fromid=%s' % (channel, openid, wechat_from)
        self.redirect(url)


class WeChatHandler(FraHandler):
    '''
        该类实际上并无存在的必要，将逐步删除对该类的依赖
    原因： 该类的存在导致部署新客户变得麻烦，需要修改重定向的链接
            扩展性太差
    '''

    def get(self, channel, wechat_from):
        """
        :param channel: 
        :param wechat_from: 微信的OPENID，该值指示此次分享者的openid
        :return: 
        """
        log.debug('Get Request')
        log.debug('Channel is:%s' % (channel))
        #
        # 跳转至该链接时，会自动加上?openid参数
        openid = self.get_argument('openid')
        log.info("openid=%s" % (openid))
        url = 'http://www.fenweiplus.com/?channel=%s&openid=%s&fromid=%s#score' % (channel, openid, wechat_from)

        # postdata = urllib.parse.urlencode({
        #     "openid": openid
        # })
        # uurl = 'http://wx.zhishixia.com/wechat/getuser'
        # headers = {
        #     "Content-type": "text/json; charset:UTF-8"
        # }
        # req = urllib.request.Request(uurl, postdata, headers)
        # r = urllib.request.urlopen(req)
        # print(r.read().decode('utf-8'))

        self.redirect(url)
        """
        signature = self.get_argument('signature')
        timestamp = self.get_argument('timestamp')
        nonce = self.get_argument('nonce')
        echostr = self.get_argument('echostr')

        token = 'c50bddbea00b4d8cbac8cb1601a14acd'

        log.info('signature:%s'%(signature))
        log.info('timestamp:%s'%(timestamp))
        log.info('nonce is: %s'%(nonce))
        log.info('echostr is: %s'%(echostr))

        try:
            list = [token, timestamp, nonce]
            list.sort()
            listr = ''.join(list)
            hashcode = hashlib.sha1(listr.encode()).hexdigest()
            log.info("handle get:%s, signature is: %s" % (hashcode, signature))
            if hashcode == signature:
                self.write(echostr)
            else:
                self.write('')
        except Exception as e:
            print(e)
            self.write('error')
        """

    def post(self, *args, **kwargs):
        log.info('收到Post请求')
        params = self.request.body
        params = json.loads(params.decode('utf-8'))
        log.info('params: %s' % (params))
        log.info("==========================")
        ret = {}
        ret['code'] = 200
        ret['msg'] = 'ok'
        ret['url'] = 'http://www.fractalplus.cn'
        self.write(json.dumps(ret))


def make_app():
    settings = {
        'cookie_secret': "1988",
        'xsrf_cookies': False
    }

    return tornado.web.Application(
        handlers=[
            (r"/8c2013f0-dfa4-4310-8fd0-854416a346ad", WeChatHandler)
        ], **settings)


def test():
    sig = '1fdb77f3dacb1969244b16b861457f1d88f21f41'
    times = '1505400055'
    none = '909238983'
    token = 'c50bddbea00b4d8cbac8cb1601a14acd'
    lst = [token, times, none]
    lst.sort()
    lstr = ''.join(lst)
    code = hashlib.sha1(lstr.encode()).hexdigest()

    print(code)


if __name__ == '__main__':
    test()
    exit(0)
    log.info('启动服务器。。。。')
    app = make_app()
    app.listen(7070)
    log.info('已启动')
    io = tornado.ioloop.IOLoop.current()
    sp = SigProccess(io)
    io.start()
